<?php
/**
 *+------------------
 * madong
 *+------------------
 * Copyright (c) https://gitee.com/motion-code  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Official Website: http://www.madong.tech
 */

namespace madong\laravel\wf\services;

use madong\laravel\wf\basic\BaseService;
use madong\helper\Pagination;
use madong\ingenious\ex\LFlowException;
use madong\ingenious\interface\model\IProcessDefineFavorite;
use madong\ingenious\interface\services\IProcessDefineFavoriteService;
use madong\ingenious\libs\utils\ArrayHelper;
use madong\ingenious\libs\utils\AssertHelper;
use madong\ingenious\libs\utils\PropertyCopier;
use madong\laravel\wf\dao\ProcessDefineFavoriteDao;

class ProcessDefineFavoriteService extends BaseService implements IProcessDefineFavoriteService
{

    public function __construct()
    {
        $this->dao = new ProcessDefineFavoriteDao();
    }

    public function created($param): ?IProcessDefineFavorite
    {
        unset($param->id);
        AssertHelper::notNull($param->process_define_id ?? '', '参数ID不能为空');
        $model = $this->dao->get(['process_define_id' => $param->process_define_id, 'user_id' => $param->user_id]);
        if (!empty($model)) {
            return $model;
        }
        $model = $this->dao->getModel();
        PropertyCopier::copyProperties($param, $model);
        return $this->dao->save($model->toArray());
    }

    public function del(string|array|int $data): array
    {
        return $this->transaction(function () use ($data) {
            try {
                $data       = ArrayHelper::normalize($data);
                $deletedIds = [];
                foreach ($data as $id) {
                    $item = $this->dao->get($id);
                    if (!$item) {
                        continue; // 如果找不到项，跳过
                    }
                    $item->delete();
                    $primaryKey   = $item->getPk();
                    $deletedIds[] = $item->{$primaryKey};
                }
                return $deletedIds;
            } catch (\Throwable $e) {
                throw new LFlowException($e->getMessage());
            }
        });
    }

    public function list($param): array
    {
        $where = ArrayHelper::filterArray(ArrayHelper::paramsFilter($param, [
            ['user_id', ''],
            ['process_define_id', ''],
        ]));
        [$page, $limit] = Pagination::getPageValue($param);
        [$items, $total] = $this->dao->getList($where, ['*'], $page, $limit, '', []);
        return compact('items', 'total');
    }

    public function findById(string $id): ?IProcessDefineFavorite
    {
        return $this->dao->get($id);
    }

}
